var GuaGame = function (fps, imags) {
    // loads 是一个对象，里面是图片的名字和路径

    var g = {
                    actions:{},
                    keydowns:{},
                    images:{},
    }
    
    var canvas = document.querySelector('#id-canvas')
    var context = canvas.getContext('2d')
    
    g.canvas = canvas
    g.context = context
    // draw game
    g.drawImage = function (guaImage) {
    
                    g.context.drawImage(guaImage.image, guaImage.x, guaImage.y)
    
    }
    // events
    window.addEventListener('keydown', function(event){
                    g.keydowns[event.key] = true
    })
    window.addEventListener('keyup', function(event){
                    g.keydowns[event.key] = false
    })
    // 
    g.registerAction = function (key, callback) {
                    g.actions[key] = callback
                    
    }
    //timer
    window.fps = 30
    var runloop = function (){
        // events
        var actions = Object.keys(g.actions)
        for (var i = 0; i < actions.length; i++){
            var key = actions[i]
            if(g.keydowns[key])
            {
                // if key down ,call callback action
                g.actions[key]()
            }
        }

        //update
        g.update()                                
        context.clearRect(0, 0, canvas.width, canvas.height)
        //draw
        g.draw()
        
        //next run
        setTimeout(function() {
            runloop()
        }, 1000/window.fps);
}

    var loads = []
    // 预先载入所有图片
    var names = Object.keys(images)
    for (var i = 0; i < names.length; i++) {
        var name = names[i]
        var path = imags[name]
        var img = new Image()
        img.src = path
        img.onload = function(){
            // 所有图片都加载之后，调用run
            g.images[name]=img
            loads.push(1)
            if(loads.length == imags.length)
            {
                g.run()
            }
        }
        

    }
    game.imageByName = function (name){
        var img = g.images[name]
        var image = {
            w:img.width,
            h:img.height,
            image:img,
        }
        return image
    }
    g.run = function(){
        // 开始运行程序
        setTimeout(function() {
            runloop()
    }, 1000/window.fps);
    }




          
    return g
}